package com.javainterface.controller;


import cn.coremail.apiws.API2;
import cn.coremail.apiws.API2_Service;
import cn.coremail.apiws.ReturnInfo;
import com.javainterface.service.CoreMailService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * 调用CoreMail方法，获取该用户邮件
 * appId:CoreMail账户
 * secret:CoreMail密码
 */
@Controller
@RequestMapping("/email")
public class CoreMailController {

    @Autowired
    CoreMailService coreMailService;

    //获取Token
    public String getMailToken(String appId, String secret) throws MalformedURLException {
        String url = "https://mail.behc.com.cn/apiws/services/API2?wsdl";
        API2 apiPort = (new API2_Service(new URL(url))).getAPI2Port();
        ReturnInfo returnInfo = apiPort.requestToken(appId, secret);
        return returnInfo.getResult();
    }

    @PostMapping ("/getCoreMailList")
    @ResponseBody
    public JSONObject getCoreMailList(String appId) throws Exception {
        System.out.println("getCoreMailList------>appId:"+appId);
        String url = "https://mail.behc.com.cn/apiws/services/API2?wsdl";
        API2 apiPort = (new API2_Service(new URL(url))).getAPI2Port();
        String token = getMailToken("apiceshi@behc.com.cn", "Admin@001");
        ReturnInfo mailXml = apiPort.getNewMailInfos(token, appId, "format=xml&limit=10");
        JSONObject json = coreMailService.xmlToJson_MailList(appId, token, mailXml.getResult());
        System.out.println(json);
        return json;
    }
}
